package com.ecb.business.service.impl;

import com.ecb.business.dto.app.AppDTO;
import com.ecb.business.dto.app.QueryAppDTO;
import com.ecb.business.exception.BusinessException;
import com.ecb.business.po.ChainAppPO;
import com.ecb.business.repository.ChainAppDao;
import com.ecb.business.service.AppService;
import com.ecb.business.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class AppServiceImpl implements AppService {
    @Autowired
    private ChainAppDao chainAppDao;
    @Override
    public List<AppDTO> getAllApp(QueryAppDTO queryDTO) {
        List<ChainAppPO> result = chainAppDao.findAllByAppNameOrAppCodeAndStatusEquals(queryDTO.getAppCode(), queryDTO.getAppName(), 1);
        List<AppDTO> appDTOS = JsonUtils.beanToArray(result, AppDTO.class);
        return appDTOS;
    }

    @Override
    public boolean addApp(AppDTO addDTO) {
        ChainAppPO appPO = new ChainAppPO();
        appPO.setStatus(1);
        appPO.setAppCode(addDTO.getAppCode());
        appPO.setAppName(addDTO.getAppName());
        appPO.setCreateTime(new Date());
        appPO.setModifyTime(new Date());
        chainAppDao.save(appPO);
        return true;
    }

    @Override
    public boolean updateApp(AppDTO appDTO) {
        Optional<ChainAppPO> byId = chainAppDao.findById(appDTO.getId());
        if (!byId.isPresent()){
            throw new BusinessException(500, "应用不存在");
        }
        ChainAppPO appPO = byId.get();
        appPO.setAppCode(appDTO.getAppCode());
        appPO.setAppName(appDTO.getAppName());
        chainAppDao.save(appPO);
        return true;
    }

    @Override
    public boolean deleteApp(AppDTO appDTO) {
        Optional<ChainAppPO> byId = chainAppDao.findById(appDTO.getId());
        if (!byId.isPresent()){
            throw new BusinessException(500, "应用不存在");
        }
        ChainAppPO appPO = byId.get();
        appPO.setStatus(9);
        appPO.setModifyTime(new Date());
        chainAppDao.save(appPO);
        return true;
    }
}
